/*
 * @Author: YuanSong
 * @Date: 2021-12-13 21:45:48
 * @Last Modified by: YuanSong
 * @Last Modified time: 2022-01-18 22:39:22
 */

import React from "react";
import NormalPage from "@components/NormalPage";
import { withRouter, RouteComponentProps } from "react-router-dom";
import Socket from '@api/socket';
import flvjs from 'flv.js';
import { message } from "@components/Message";
type IProps = RouteComponentProps & {
  match:{
    params:{
      room_id:string}
    }
};
interface VideoRoom {
  taskRemindInterval:NodeJS.Timeout | null,
  socket:Socket
}
class VideoRoom extends React.Component<IProps> {
  constructor(props: any) {
    super(props);
    this.taskRemindInterval = null;
  }
  readonly state={
    taskStage:'',
    currentViewersNumber:0,
  }
  componentDidMount(){
   
    if (!this.props.match.params.room_id){
      message({content:'地址栏参数有误',type:'success'});
    }
    this.socket = new Socket({
      //production <-----> dev
      // socketUrl:'ws://127.0.0.1:9001',
      socketUrl:'ws://47.98.233.31:9001',
      timeout:5000,
      socketMessage:(receive:any)=>{
        console.log(receive);//后端返回的数据
        if (!receive.data){
          return;
        }
        let data = JSON.parse(receive.data)
        
        if (data.viewersNumer){
          this.setState({
            currentViewersNumber:data.viewersNumer
          })
        }
        
      },
      socketClose:(msg:any)=>{
        console.log(msg);
        this.taskRemindInterval && clearInterval(this.taskRemindInterval);
      },
      socketError:()=>{
        console.log(this.state.taskStage+'连接建立失败');
      },
      socketOpen:()=>{
        console.log('连接建立成功');
        this.socket.sendMessage && this.socket.sendMessage({'startPullStream':`start pull stream ${this.props.match.params.room_id}`})
        //心跳机制 定时向后端发送数据
        this.taskRemindInterval = setInterval(()=>{
          this.socket.sendMessage && this.socket.sendMessage({heartBeat:'server,are you alive?'})
        },6000)
      }
    });
    //尝试创建socket连接
    let trySuccess = false;
    try {
      this.socket.connection()
    } catch(e){
      //捕获异常，防止js error
      //donothing
    }

    if (flvjs.isSupported()){
      var videoElement = document.getElementById('videoElement');
      var flvPlayer = flvjs.createPlayer({
        type:'flv',
        //production <-----> dev
        // url:'http://localhost:8000/live/test.flv'
        url:'http://47.98.233.31:8000/live/test.flv'
      });
      if (videoElement instanceof HTMLMediaElement){
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
        flvPlayer.play();
      }
      
    }
   
    
  }
  componentWillUnmount(){
    console.log('unmount video room')
    try {
      this.socket.closeSocket()
    } catch(e){
      //捕获异常，防止js error
      //donothing
    }
  }
  render() {
    return (
      <NormalPage showHeader={true} showRightNavigation={true}>
        <div className="Video-Room-Wrapper">
          <p className="Viewers-Number">当前观影人数：{this.state.currentViewersNumber}</p>
          <video id="videoElement" style={{margin:'20px',width:'80%',height:'600px'}} controls={true}></video>
        </div>
        
      </NormalPage>
    );
  }
}
export default withRouter(VideoRoom);
